<template>
  <div class="app-container">
    <div v-show="!batchDataInfo.visible && !singleDataInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :filter-btn="filterInfo.btnList"
        >
          <template v-slot:filter-confirmConsumption>
            <el-button
              @click="confirmConsumption()"
              :disabled="!tableInfo.selections.length"
              >确认消耗</el-button
            >
          </template>
          <template v-slot:filter-stockTransfer>
            <el-button @click="stockTransfer()" :disabled="hasDisabled1"
              >移库</el-button
            >
          </template>
          <template v-slot:filter-purchaseReturn>
            <el-button @click="purchaseReturn()" :disabled="hasDisabled2"
              >采购退货</el-button
            >
          </template>
          <template v-slot:filter-scrap>
            <el-button @click="scrap()" :disabled="hasDisabled1"
              >报废</el-button
            >
          </template>
          <template v-slot:filter-depotReturn>
            <el-button
              @click="depotReturn()"
              :disabled="!tableInfo.selections.length"
              >退回本仓库</el-button
            > </template
          ><template v-slot:filter-collectReturn>
            <el-button @click="collectReturn()" :disabled="hasDisabled1"
              >领用退回</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :tabIndex="true"
        :selectable="selectable"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span>{{ scope.row.orderNo }}</span>
        </template>
      </TableContainer>
    </div>

    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <!-- 批量操作 -->
    <BatchData
      v-if="batchDataInfo.visible"
      v-model:visible="batchDataInfo.visible"
      :title="batchDataInfo.title"
      :btnCode="batchDataInfo.btnCode"
      :idNot="batchDataInfo.idNot"
      :selectionsData="tableInfo.selections"
      @returnBack="getList"
    />
    <!-- 单行操作 -->
    <SingleData
      v-if="singleDataInfo.visible"
      :title="singleDataInfo.title"
      :btnCode="singleDataInfo.btnCode"
      :rowsData="rowsData"
      :idNot="singleDataInfo.idNot"
      v-model:visible="singleDataInfo.visible"
      @returnBack="getList"
    />
  </div>
</template>

<script setup name="smartCabinetPendOutRecord">
import { getSmartCabinetPendOutRecordCustomizeListPage } from '@/api/smartCabinet.js'
import BatchData from './batchData'
import SingleData from './singleData'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getDeptAll, getDepotAll } from '@/api/core'
const { proxy } = getCurrentInstance()
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      depotAuth: {
        asTbName: 'smart_cabinet_list',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
      deptAuth: {
        asTbName: 'smart_cabinet_list',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'stockTransfer',
      event: stockTransfer,
      label: '移库',
      show: proxy.$permission('smartCabinetPendOutRecord:transferDepot'),
    },
    {
      type: 'slot',
      value: 'confirmConsumption',
      event: confirmConsumption,
      label: '确认消耗',
      show: proxy.$permission('smartCabinetPendOutRecord:consumeConfirm'),
    },

    {
      type: 'slot',
      value: 'purchaseReturn',
      event: purchaseReturn,
      label: '采购退货',
      show: proxy.$permission('smartCabinetPendOutRecord:purchReturn'),
    },
    {
      type: 'slot',
      value: 'scrap',
      event: scrap,
      label: '报废',
      show: proxy.$permission('smartCabinetPendOutRecord:scrapExport'),
    },
    {
      type: 'slot',
      value: 'depotReturn',
      event: depotReturn,
      label: '退回本仓库',
      show: proxy.$permission('smartCabinetPendOutRecord:returnDepot'),
    },
    {
      type: 'slot',
      value: 'collectReturn',
      event: collectReturn,
      label: '领用退回',
      show: proxy.$permission('smartCabinetPendOutRecord:useReturnExport'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        event: stockTransfer,
        label: '移库',
        show: proxy.$permission('smartCabinetPendOutRecord:transferDepot'),
        ifRender: function (row) {
          return row.processStatus === 0
        },
      },
      {
        event: confirmConsumption,
        label: '确认消耗',
        show: proxy.$permission('smartCabinetPendOutRecord:consumeConfirm'),
        ifRender: function (row) {
          return row.processStatus === 0
        },
      },
      {
        event: purchaseReturn,
        label: '采购退货',
        show: proxy.$permission('smartCabinetPendOutRecord:purchReturn'),
        ifRender: function (row) {
          return row.processStatus === 0
        },
      },
      {
        event: scrap,
        label: '报废',
        show: proxy.$permission('smartCabinetPendOutRecord:scrapExport'),
        ifRender: function (row) {
          return row.processStatus === 0
        },
      },
      {
        event: depotReturn,
        label: '退回本仓库',
        show: proxy.$permission('smartCabinetPendOutRecord:returnDepot'),
        ifRender: function (row) {
          return row.processStatus === 0
        },
      },
      {
        event: collectReturn,
        label: '领用退回',
        show: proxy.$permission('smartCabinetPendOutRecord:useReturnExport'),
        ifRender: function (row) {
          return row.processStatus === 0
        },
      },
    ],
  },
})
const batchDataInfo = ref({
  visible: false,
  idNot: '',
  title: '',
})
const singleDataInfo = ref({
  visible: false,
  idNot: '',
  title: '',
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const rowsData = ref({})
// 同库房数据才能批量操作
const hasDisabled1 = computed(() => {
  if (!tableInfo.value.selections.length) return true
  const ids = tableInfo.value.selections.map(
    (value) => value.smartCabinetDepotId
  )
  const noRepeatIds = [...new Set(ids)]
  batchDataInfo.value.idNot = noRepeatIds.length ? noRepeatIds.join(',') : ''
  if (noRepeatIds.length !== 1) return true
  return false
})
// 同库房同供应商
const hasDisabled2 = computed(() => {
  if (!tableInfo.value.selections.length) return true
  const depotIds = tableInfo.value.selections.map(
    (value) => value.smartCabinetDepotId
  )
  const supplierIds = tableInfo.value.selections.map(
    (value) => value.supplierId
  )
  const noRepeatDepotIds = [...new Set(depotIds)]
  const noRepeatSupplierIds = [...new Set(supplierIds)]
  if (noRepeatDepotIds.length !== 1 || noRepeatSupplierIds.length !== 1) {
    return true
  }
  return false
})

onMounted(() => {
  let obj = {
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: true,
      type: 'column',
      hidden: false,
    },
    smartCabinetCode: {
      label: '智能柜编码',
      value: 'smartCabinetCode',
      componentType: 'input',
      show: false,
      hidden: true,
    },
    smartCabinetName: {
      label: '智能柜名称',
      value: 'smartCabinetName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
    smartCabinetTypeValue: {
      label: '智能柜类型',
      value: 'smartCabinetTypeValue',
      asValue: 'smartCabinetType',
      componentType: 'select-model',
      code: 'smart_cabinet_type',
      show: false,
      hidden: true,
    },
    factoryMainCode: {
      label: '原厂主码',
      value: 'factoryMainCode',
      componentType: 'input',
      show: true,
      type: 'column',
      hidden: false,
    },
    factorySubCode: {
      label: '原厂从码',
      value: 'factorySubCode',
      componentType: 'input',
      show: true,
      type: 'column',
      hidden: false,
    },
    smartCabinetDepotName: {
      label: '所属仓库',
      value: 'smartCabinetDepotName',
      asValue: 'smartCabinetDepotId',
      componentType: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '1',
      },
      api: getDepotAll,
      show: false,
      hidden: true,
    },
    smartCabinetDeptName: {
      label: '所属部门',
      value: 'smartCabinetDeptName',
      asValue: 'smartCabinetDeptId',
      query: {
        deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      show: false,
      hidden: true,
    },
    accessAccount: {
      label: '取用人账号',
      value: 'accessAccount',
      componentType: 'input',
      show: true,
      type: 'column',
      hidden: false,
    },
    accessUserName: {
      label: '取用人',
      value: 'accessUserName',
      asValue: 'accessUserId',
      componentType: 'select-user',
      highlightRow: true,
      checkBox: false,
      show: false,
      hidden: true,
    },
    accessDeptName: {
      label: '取用部门',
      value: 'accessDeptName',
      asValue: 'accessDeptId',
      query: {
        deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      show: false,
      hidden: true,
    },
    accessTime: {
      label: '取用时间',
      value: 'accessTime',
      componentType: 'datetimerange',
      show: false,
      hidden: true,
    },
    processStatusValue: {
      label: '处理状态',
      value: 'processStatusValue',
      asValue: 'processStatus',
      componentType: 'select-model',
      code: 'smart_cabinet_process_status',
      show: false,
      hidden: true,
    },
    processTypeValue: {
      label: '处理类型',
      value: 'processTypeValue',
      asValue: 'processType',
      componentType: 'select-model',
      code: 'smart_cabinet_process_type',
      show: false,
      hidden: true,
    },
    processOrderNo: {
      label: '处理单号',
      value: 'processOrderNo',
      componentType: 'input',
      show: true,
      type: 'column',
      hidden: false,
    },
    processUserName: {
      label: '处理人',
      value: 'processUserName',
      asValue: 'processUser',
      componentType: 'select-user',
      highlightRow: true,
      checkBox: false,
      show: false,
      hidden: true,
    },
    processTime: {
      label: '处理时间',
      value: 'processTime',
      componentType: 'datetimerange',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
})
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  let arr = [
    {
      asTbName: 'smart_cabinet_list',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
    {
      asTbName: 'smart_cabinet_list',
      columnName: 'dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
function selectable(obj) {
  if (obj.processStatus) {
    return false
  } else {
    return true
  }
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 初始化验证
function initRules() {
  formInfo.value.rules = proxy.$initRules(formInfo.value.fieldList)
}
function confirmConsumption(row) {
  if (!row) {
    btnHandle('确认消耗')
  } else {
    btnHandle('确认消耗', row)
  }
}
function stockTransfer(row) {
  if (!row) {
    btnHandle('移库')
  } else {
    btnHandle('移库', row)
  }
}
function purchaseReturn(row) {
  if (!row) {
    btnHandle('采购退货')
  } else {
    btnHandle('采购退货', row)
  }
}
function scrap(row) {
  if (!row) {
    btnHandle('报废')
  } else {
    btnHandle('报废', row)
  }
}
function depotReturn(row) {
  if (!row) {
    btnHandle('退回本仓库')
  } else {
    btnHandle('退回本仓库', row)
  }
}
function collectReturn(row) {
  if (!row) {
    btnHandle('领用退回')
  } else {
    btnHandle('领用退回', row)
  }
}
function btnHandle(title, row) {
  let btnCode = ''
  filterInfo.value.btnList.forEach((item) => {
    if (item.label === title) {
      btnCode = item.value
    }
  })
  if (!row) {
    batchDataInfo.value.title = title
    batchDataInfo.value.btnCode = btnCode
    batchDataInfo.value.visible = true
  } else {
    singleDataInfo.value.title = title
    singleDataInfo.value.btnCode = btnCode
    rowsData.value = row
    singleDataInfo.value.idNot = row.smartCabinetDepotId
    singleDataInfo.value.visible = true
  }
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    // 对表格获取到的数据做处理
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'smartCabinetPendOutRecord-com.slip.spd.entity.vo.smartCabinet.SmartCabinetPendOutRecordVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getSmartCabinetPendOutRecordCustomizeListPage
      getList()
    }
  })
}
</script>

<style scoped></style>
